package com.mdd.common.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @author 杨正印
 * @date 2023/11/1
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public final static String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";

    public final static String CAL_FORMAT = "yyyy-MM-dd";

    public static final String DATE_FORMAT_MM= "yyyyMM";


    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");


    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYY_MM_DD_HH  = "yyyy-MM-dd HH";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String HH_MM_SS = "HH:mm:ss";
    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};


    private static SimpleDateFormat sDateFormat = null;

    public static  Date dateFormat(String dateTime) {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        try {
            return sdf.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 获取当前日期时间yyyyMMddHHmmss
     */
    public static String getDateTimeToymd() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date());
    }

    /**
     * 获取当前日期
     */
    public static String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(new Date());
    }

    public static String getDateOfPattern(String originalDateStr) {
        LocalDate originalDate = LocalDate.parse(originalDateStr);

        // 定义目标日期格式
        DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        return originalDate.format(targetFormatter);
    }

    public static String getDateHourIsZero() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);  // 将小时设为0
        calendar.set(Calendar.MINUTE, 0);       // 将分钟设为0
        calendar.set(Calendar.SECOND, 0);       // 将秒数设为0
        Date date = calendar.getTime();         // 获取时间对象
        String dateString = sdf.format(date);   // 格式化时间对象
        return dateString;
    }



    /**
     * 获取昨日时间时分秒为0格式
     * @return
     */
    public static String getYesterdayDateHourIsZero() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);  // 获取昨天日期
        calendar.set(Calendar.HOUR_OF_DAY, 0);    // 将小时设为0
        calendar.set(Calendar.MINUTE, 0);         // 将分钟设为0
        calendar.set(Calendar.SECOND, 0);         // 将秒数设为0
        Date date = calendar.getTime();           // 获取时间对象
        String dateString = sdf.format(date);     // 格式化时间对象
        return dateString;
    }

    /**
     * 获取昨天的最后一刻
     * @return
     */
    public static String getYesterdayDateHourLater() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);  // 获取昨天日期
        calendar.set(Calendar.HOUR_OF_DAY, 23);    // 将小时设为0
        calendar.set(Calendar.MINUTE, 59);         // 将分钟设为0
        calendar.set(Calendar.SECOND, 59);         // 将秒数设为0
        Date date = calendar.getTime();           // 获取时间对象
        String dateString = sdf.format(date);     // 格式化时间对象
        return dateString;
    }
    /**
     * 获取当前日期时间
     */
    public static String getDateTimeToYmd() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSSS");
        return sdf.format(new Date());
    }
    /**
     * 获取当前时间
     */
    public static String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(new Date());
    }


    /**
     * 获取距离当前时间 n 天前的时间
     *
     * @param days timeFormat
     * @return
     */
    public static String getTimeBeforeDays(int days, String timeFormat) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -days);
        return new SimpleDateFormat(timeFormat).format(calendar.getTime());
    }
    public static String getAfterDay(String date, int diff) throws ParseException {
        SimpleDateFormat sdf;
        if (date.length()>10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        }
        Date parse = sdf.parse(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);
        calendar.add(Calendar.DATE, diff);
        return sdf.format(calendar.getTime());
    }

    /**
     * 将这个时间格式2018-09-10T16:00:00.000Z
     * 转为ymd 时间格式
     * @param timeStr
     * @return
     */
    public static String changeTtimeToYmd(String timeStr) {
        String dateStr = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
            Date parse = sdf.parse(timeStr.replace("Z", " UTC"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            dateStr = simpleDateFormat.format(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;

    }

    /**
     * 将时间戳转换为指定格式的日期字符串
     *
     * @param seconds
     * @param format
     * @return
     */
    public static String changeTimeStampToDateStr(String seconds, String format) {
        if (StringUtils.isEmpty(seconds)) {
            return "";
        }
        if (StringUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));

    }


    /**
     * 将时间戳转换为指定格式的日期字符串
     * @param
     * @param format
     * @return
     */
    public static String changeDateStrToTimeStamp(String dateStr, String format) {
        String timeStamp = "";
        try {
            if (StringUtils.isEmpty(dateStr)) {
                return "";
            }
            if (StringUtils.isEmpty(format)) {
                format = "yyyy-MM-dd HH:mm:ss";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            timeStamp = String.valueOf(sdf.parse(dateStr).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeStamp;
    }

    /**
     * 将时间戳转换为特定格式的日期字符串
     * @param timestamp
     * @return
     */
    public static String formatTimestampToDateTime(String timestamp) {
        long millis = Long.parseLong(timestamp);

        // 创建一个Calendar实例并设置时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);

        // 格式化为指定的日期时间字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
     * @throws ParseException
     */
    public static int daysBetween(Date smdate, Date bdate) {
        int daysBetween = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bdate);
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);
            daysBetween = Integer.parseInt(String.valueOf(between_days));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return daysBetween;
        }
    }

    /**
     　　 *字符串的日期格式的计算
     　　 */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1 = cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    public static synchronized String date2Str(Long time) {
        Date date = new Date(time);
        sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sDateFormat.format(date);
    }

    public static synchronized String date2Str(Date time) {
        sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sDateFormat.format(time);
    }

    public static synchronized String date2Str(Date time, String pattern) {
        sDateFormat = new SimpleDateFormat(pattern);
        return sDateFormat.format(time);
    }

    //截取yyyy-MM-dd HH:mm:ss  前面的日期yyyy-MM-dd

    public static String  InterceptionDate(String date){
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date dateTime = inputFormat.parse(date);
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
            date = outputFormat.format(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    /**
     　　 *字符串的日期相减得到月份
     */
    public static int monthBetween(String start,String end) {
        String endStr = InterceptionDate(end);
        String startStr = InterceptionDate(start);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate startDate = LocalDate.parse(startStr, formatter);
        LocalDate endDate = LocalDate.parse(endStr, formatter);
        Period period = Period.between(
                LocalDate.of(startDate.getYear(), startDate.getMonth(), 1),
                LocalDate.of(endDate.getYear(), endDate.getMonth(), 1)
        );
        int months = period.getYears() * 12 + period.getMonths();
        return months ;
    }
    public static int yearBetween(String start,String end) {
        // 定义日期时间格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串解析为 LocalDateTime 对象
        LocalDateTime startDate = LocalDateTime.parse(start, formatter);
        LocalDateTime endDate = LocalDateTime.parse(end, formatter);

        // 获取起始日期和结束日期的年份
        int startYear = startDate.getYear();
        int endYear = endDate.getYear();
        // 计算年份差值
        int yearDifference = endYear - startYear +1;
        return yearDifference ;
    }

    public static List<String> spiltYearMonthDay(String str1 ,String str2){
        List<String> days = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate startDate = LocalDate.parse(str1, formatter);
        LocalDate endDate = LocalDate.parse(str2, formatter);
        LocalDate currentDate = endDate;
        while (!startDate.isAfter(currentDate)) {
            days.add(currentDate.toString());
            currentDate = currentDate.minusDays(1);
        }
        return days;
    }
    public static List<String>  spiltYearMonth(String str1 ,String str2){
        List<String> yearMonths = new ArrayList<>();

        // 解析日期时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime1 = LocalDateTime.parse(str1, formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(str2, formatter);

        // 获取起始年月，并将每个年月添加到List中
        YearMonth startYearMonth = YearMonth.from(dateTime1);
        YearMonth endYearMonth = YearMonth.from(dateTime2);

        YearMonth curYearMonth = endYearMonth;
        while (curYearMonth.isAfter(startYearMonth)) {
            yearMonths.add(curYearMonth.toString());
            curYearMonth = curYearMonth.minusMonths(1);
        }
        return yearMonths;
    }
    public static List<String> spiltYear(String str1, String str2) {
        List<String> years = new ArrayList<>();

        // 解析日期时间字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime1 = LocalDateTime.parse(str1, formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(str2, formatter);

        // 获取起始年份，并将每个年份添加到List中
        int startYear = dateTime1.getYear();
        int endYear = dateTime2.getYear();

        int curYear = endYear;
        while (curYear >= startYear) {
            years.add(Integer.toString(curYear));
            curYear--;
        }
        return years;
    }


    private static Map<String, String> createDataMap(String volume, String copies, String species) {
        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("volume", volume);
        dataMap.put("copies", copies);
        dataMap.put("species", species);
        return dataMap;
    }


    public static Date convertToDate(String dateString){
        if(StringUtils.isBlank(dateString)){
            return null;
        }
        try {
            String pattern ="";
            String dateStr ="";
            String[] split = dateString.split(".");
            if(split.length ==0){
                dateStr=dateString;
                pattern="yyyy";
            }else if(split.length ==2){
                dateStr=split[0]+"."+(Integer.parseInt(split[1])<10?"0"+Integer.parseInt(split[1]):split[1]);
                pattern="yyyy.MM";
            }else{
                if(!StringUtils.isBlank(split[0])){
                    dateStr+=split[0];
                    pattern="yyyy";
                }else if(!StringUtils.isBlank(split[1])){
                    dateStr+="."+(Integer.parseInt(split[1])<10?"0"+Integer.parseInt(split[1]):split[1]);
                    pattern="yyyy.MM";
                }else if(!StringUtils.isBlank(split[2])){
                    dateStr+="."+(Integer.parseInt(split[2])<10?"0"+Integer.parseInt(split[2]):split[2]);
                    pattern="yyyy.MM.dd";
                }
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
            Date date = dateFormat.parse(dateStr);
            return date;
        } catch (Exception e) {
        }
        return null;
    }

    public static Date stringDate(String dateStr, String pattem){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattem);
            if (StringUtils.isNotBlank(dateStr)) {
                return sdf.parse(dateStr);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String dateAddMonth(String date, Integer month){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parsedDate = sdf.parse(date); // 解析时间字符串为 Date 对象

            Calendar cal = Calendar.getInstance();
            cal.setTime(parsedDate); // 设置起始时间
            cal.add(Calendar.MONTH, month); // 增加指定月份

            return sdf.format(cal.getTime()); // 返回格式化后的日期字符串
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public  static  String eightTimeToNineteen(String eightTime){
        // 解析输入日期字符串为LocalDate对象
        LocalDate localDate = LocalDate.parse(eightTime, DateTimeFormatter.BASIC_ISO_DATE);

        // 构建LocalDateTime对象并设置时间为 00:00:00
        LocalDateTime localDateTime = localDate.atStartOfDay();

        // 定义输出日期时间格式
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化输出日期时间字符串
        String outputDate = localDateTime.format(outputFormatter);
        return outputDate;
    }

    public static String eightTime(String eightTime) {
        // 解析输入日期字符串为LocalDate对象
        LocalDate localDate = LocalDate.parse(eightTime, DateTimeFormatter.BASIC_ISO_DATE);

        // 构建LocalDateTime对象并设置时间为 10:00:00
        LocalDateTime localDateTime = localDate.atTime(10, 0, 0); // 这里设置小时为10，分钟和秒均为0

        // 定义输出日期时间格式
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化输出日期时间字符串
        String outputDate = localDateTime.format(outputFormatter);
        return outputDate;
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }


    public static String getApiDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd    HHmmss");
        return sdf.format(new Date());
    }
    public static final String getCurrentYear()
    {
        return dateTimeNow(YYYY);
    }
    public static final String getCurrentMonth()
    {
        return dateTimeNow(YYYY_MM);
    }
    public static final String getCurrentHour()
    {
        return dateTimeNow(YYYY_MM_DD_HH);
    }
    public static final String getHourHH()
    {
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        return  String.valueOf(hour);
    }

    public static String getCurrentHourMinusOne()
    {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 获取当前小时数
        int currentHour = now.getHour();

        // 将当前小时数减1
        int newHour = currentHour - 1;

        // 创建DateTimeFormatter对象，格式为yyyy-MM-dd HH
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");

        // 使用DateTimeFormatter对象将当前时间格式化为字符串，并减去一个小时
        String formattedDateTime = now.format(formatter) + " " + newHour;
        return formattedDateTime;
    }

    public static final String getCurrentDay()
    {
        return dateTimeNow(YYYY_MM_DD);
    }



    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 将日期转为 字符串
     * @param date
     *@param format
     * @return
     */
    public static String dateToString(Date date, String format) {
        if (date == null) {
            return null;
        }
        return new SimpleDateFormat(format).format(date);
    }
    /**
     * 将字符串转为日期
     * @param date
     *@param format
     * @return
     */
    public static Date stringToDate(String date, String format) throws ParseException {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf =new  SimpleDateFormat(format);
        return sdf.parse(date);
    }
    /**
     * 计算year年之后的时间
     * @param date
     * @param year
     * @param format
     * @return
     */
    public static String addYear(Date date, int year,String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try{
            cd.setTime(sdf.parse(sdf.format(date)));//设置calendar日期
        }catch(ParseException e){
            e.printStackTrace();
        }
        cd.add(Calendar.YEAR,year);//增加n年
        return new SimpleDateFormat(format).format(cd.getTime());
    }

    /**
     * 计算days天之后的时间
     * @param date
     * @param days
     * @param format
     * @return
     */
    public static String addDay(Date date, int days,String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try{
            cd.setTime(sdf.parse(sdf.format(date)));//设置calendar日期
        }catch(ParseException e){
            e.printStackTrace();
        }
        cd.add(Calendar.DATE,days);//增加days天
        return new SimpleDateFormat(format).format(cd.getTime());
    }

    /**
     * 计算mons月之后的时间
     * @param date
     * @param mons
     * @param format
     * @return
     */
    public static String addMonth(Date date, int mons,String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try{
            cd.setTime(sdf.parse(sdf.format(date)));//设置calendar日期
        }catch(ParseException e){
            e.printStackTrace();
        }
        cd.add(Calendar.MONTH,mons);//增加mons月
        return new SimpleDateFormat(format).format(cd.getTime());
    }

    /**
     * 获取上个月第一天
     * @return
     */
    public static String getLastMonthFirstDayStr(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date() );
        //获取当前时间上一个月
        cal.add(Calendar.MONTH, -1);
        //获取上个月的第一天
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return df.format(cal.getTime());

    }

    /**
     * 获取上个月最后一天
     * @return
     */
    public static String getLastMonthLastDayStr(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date() );
        //获取当前时间上一个月
        cal.add(Calendar.MONTH, -1);
        //获取上个月的最后一天
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
        return df.format(cal.getTime());
    }

    /**
     * 获取上周第一天
     * @return
     */
    public static String getLastWeekFirstDayStr(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calWeek = Calendar.getInstance();
        calWeek.setTime(new Date() );
        int n1 = -1;// n为推迟的周数，-1上周，0本周，1下周，2下下周，依次类推
        calWeek.add(Calendar.DATE, n1 * 7);
        //上周周一
        calWeek.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return df.format(calWeek.getTime());
    }
    /**
     * 获取上周最后一天
     * @return
     */
    public static String getLastWeekLastDayStr() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calWeek = Calendar.getInstance();
        calWeek.setTime(new Date());
        int n1 = -1;// n为推迟的周数，-1上周，0本周，1下周，2下下周，依次类推
        calWeek.add(Calendar.DATE, n1 * 7);
        //上周周日
        calWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        return df.format(calWeek.getTime());
    }

    /**
     * 计算year年之后的时间
     * @param date
     * @param year
     * @param format
     * @return
     */
    public static Date afterYearDate(Date date, int year,String format) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar cd = Calendar.getInstance();//获取一个Calendar对象
        try{
            cd.setTime(sdf.parse(sdf.format(date)));//设置calendar日期
        }catch(ParseException e){
            e.printStackTrace();
        }
        cd.add(Calendar.YEAR,year);//增加n年
        return cd.getTime();
    }
    //把时间变成下一个月份，如202102变成202103
    public static String monthAdd(String yearsMonth){
        String month = yearsMonth.substring(yearsMonth.length() - 2, yearsMonth.length());
        String years = yearsMonth.substring(0, yearsMonth.length() - 2);
        int y = Integer.parseInt(years);
        int m = Integer.parseInt(month);
        if(m == 12){
            int j = y+1;
            return j+"01";
        }else {
            int i = m+1;
            if(i <10){
                return y+"0"+i;
            }
            return y+""+i;
        }
    }
    /**
     * 获取当年的第一天
     * @param
     * @return
     */
    public static Date getCurrYearFirst(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }
    /**
     * 获取当年的下一年的第一天
     * @param
     * @return
     */
    public static Date getCurrYearLast(){
        Calendar currCal=Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, currentYear+1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }
    /**
     * 获取当前月份的第一天
     * @param
     * @return
     */
    public static Date getMonthFirst(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
    /**
     * 获取当前月份的下一月份的第一天
     * @param
     * @return
     */
    public static Date getMonthLast(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH,  calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }
    public static void main(String[] args) {
//        System.out.println(getDateHourIsZero());
//        LocalDate startDate = LocalDate.of(2023, 12, 1);
//        LocalDate endDate = LocalDate.of(2010, 1, 1);
//
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
//
//        YearMonth currentMonth = YearMonth.from(startDate);
//        while (!currentMonth.isBefore(YearMonth.from(endDate))) {
//            int year = currentMonth.getYear();
//            int month = currentMonth.getMonthValue();
//            LocalDate firstDayOfMonth = currentMonth.atDay(1);
//            LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
//
//            System.out.println("Year: " + year + ", Month: " + month);
//            System.out.println("First day of month: " + formatter.format(firstDayOfMonth));
//            System.out.println("Last day of month: " + formatter.format(lastDayOfMonth));
//            System.out.println();
//
//            currentMonth = currentMonth.minusMonths(1);
//        }
//        List<String> startMonthToEndMonth = getStartMonthToEndMonth();
//        System.out.println(startMonthToEndMonth);
//        List<String> startMonthToEndMonth = getStartMonthToEndMonth(2010, 2024);
//        System.out.println(startMonthToEndMonth)

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("TEST",5);
        wrapper.like("KKd","9");
        //==
        System.out.println(wrapper.getCustomSqlSegment());

        System.out.println(wrapper.getSqlSegment());

        System.out.println(wrapper.getTargetSql());

        System.out.println(wrapper.getExpression().getSqlSegment());
        System.out.println(wrapper.getParamNameValuePairs());
        System.out.println(wrapper.toString());


    }
    public static List<String> getStartMonthToEndMonth(int yearStart,int yearEnd){
            LocalDate startDate = LocalDate.of(yearEnd, 12, 1);
            LocalDate endDate = LocalDate.of(yearStart, 1, 1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

            YearMonth currentMonth = YearMonth.from(startDate);
            List<String>  list = new ArrayList<>();
        while (!currentMonth.isBefore(YearMonth.from(endDate))) {
                int year = currentMonth.getYear();
                int month = currentMonth.getMonthValue();
                LocalDate firstDayOfMonth = currentMonth.atDay(1);
                LocalDate lastDayOfMonth = currentMonth.atEndOfMonth();
                list.add(formatter.format(firstDayOfMonth));
                currentMonth = currentMonth.minusMonths(1);
            }
            return list;
    }
//        System.out.println(getCurrYearLast());
//        System.out.println(dateToString(getCurrYearLast(),YYYY_MM_DD_HH_MM_SS));
//        System.out.println(getCurrYearFirst());
//        System.out.println(dateToString(getCurrYearFirst(),YYYY_MM_DD_HH_MM_SS));
//        System.out.println(getMonthFirst());
//        System.out.println(dateToString(getMonthFirst(),YYYY_MM_DD_HH_MM_SS));
//        System.out.println(getMonthLast());
//        System.out.println(dateToString(getMonthLast(),YYYY_MM_DD_HH_MM_SS));
//        System.out.println(getHourHH());
//
//        System.out.println("sddddd");
//        // 获取当前时间
//        LocalDateTime now = LocalDateTime.now();
//
//        // 获取当前小时数
//        int currentHour = now.getHour();
//
//        // 将当前小时数减1
//        int newHour = currentHour - 1;
//
//        // 创建DateTimeFormatter对象，格式为yyyy-MM-dd HH
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
//
//        // 使用DateTimeFormatter对象将当前时间格式化为字符串，并减去一个小时
//        String formattedDateTime = now.format(formatter) + " " + newHour;
//
//        // 打印结果
//        System.out.println(formattedDateTime);
//        Calendar calendar = Calendar.getInstance();
//        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//        System.out.println("当前小时数：" + hour);


    /**
     * 距离当前时间还剩多少秒
     * @param currentDate
     * @return
     */
    public static Integer getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }

    public static List<String> getStartYearToEndYear(int yearStart, int yearEnd) {
        LocalDate startDate = LocalDate.of(yearEnd, 12, 1);
        LocalDate endDate = LocalDate.of(yearStart, 1, 1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");

        YearMonth currentMonth = YearMonth.from(startDate);
        List<String> list = new ArrayList<>();

        while (!currentMonth.isBefore(YearMonth.from(endDate))) {
            int year = currentMonth.getYear();
            list.add(formatter.format(currentMonth.atDay(1)));

            // Move to the next year
            currentMonth = currentMonth.minusYears(1);
        }

        return list;
    }

    /**
     * 获取当前日期时间
     */
    public static String getDateTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }

    public static String fiveDaysBeforeCurrentDateTime() {
        // 获取当前日期时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 获取当前日期时间之前的第5天
        LocalDateTime dateTimeBefore5Days = currentDateTime.minusDays(5);

        // 格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = dateTimeBefore5Days.format(formatter);

        return formattedDateTime;
    }

    private final static SimpleDateFormat sdf = new SimpleDateFormat(CAL_FORMAT);


    public static String convertToEndOfDay(String date) {

        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(YYYY_MM_DD);

        LocalDate localDate = LocalDate.parse(date, inputFormatter);

        String result = localDate.atTime(23, 59, 59).toString();  // 转换为 LocalDateTime

        return result.replace("T", " ");
    }


    public static boolean isValidFormat(String dateStr) {
        try {
            LocalDateTime.parse(dateStr, FORMATTER);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Integer stringDateToInt(String date){
        String[] parts = date.split("-");
        String formattedDate = parts[0] + parts[1] + parts[2];
        return Integer.parseInt(formattedDate);
    }

    /**
     * 获取n天后 周几
     *
     * @param daysInFuture
     * @return
     */
    public static String dayOfWeek(Integer daysInFuture) {
        if (daysInFuture == 0) {
            return "今天";
        }
        if (daysInFuture == 1) {
            return "明天";
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, daysInFuture);
        // 获取星期几
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        String weekName;
        switch (dayOfWeek) {
            case Calendar.SUNDAY:
                weekName = "周日";
                break;
            case Calendar.MONDAY:
                weekName = "周一";
                break;
            case Calendar.TUESDAY:
                weekName = "周二";
                break;
            case Calendar.WEDNESDAY:
                weekName = "周三";
                break;
            case Calendar.THURSDAY:
                weekName = "周四";
                break;
            case Calendar.FRIDAY:
                weekName = "周五";
                break;
            case Calendar.SATURDAY:
                weekName = "周六";
                break;
            default:
                weekName = "";
                break;
        }
        return weekName;
    }

    /**
     * 获取n天后 MM-DD
     *
     * @param daysInFuture
     * @return
     */
    public static String getMonthDay(Integer daysInFuture) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 当前日期之后的天数
        LocalDate futureDate = today.plusDays(daysInFuture);
        if (Objects.nonNull(futureDate)) {
            return futureDate.toString().substring(5, 10);
        }
        return "";
    }

    /**
     * 获取几个小时后的时间
     *
     * @param hourInFuture
     * @return
     */
    public static Long getAddNumTime(Integer hourInFuture) {
        // 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime futureDateTime = now.plusHours(hourInFuture);
        return getLocalDateTime(futureDateTime);
    }

    /**
     * 将 LocalDateTime 转换为时间戳（毫秒）
     *
     * @param dateTime
     * @return
     */
    public static Long getLocalDateTime(LocalDateTime dateTime) {
        // 转换为ZonedDateTime，默认时区
        ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.systemDefault());

        // 转换为Instant
        java.time.Instant instant = zonedDateTime.toInstant();

        // 获取自1970年1月1日00:00:00 GMT以来的毫秒数
        Long millis = instant.toEpochMilli();

        return millis;
    }

    /**
     * 获取当前日期 时间的毫秒
     *
     * @param time
     * @return
     */
    public static Long getLongNowTime(String time) {
        LocalDate now = LocalDate.now();
        LocalDateTime localDateTime = now.atStartOfDay();
        String dateTime = localDateTime.toString().replace("00:00", time);
        localDateTime = LocalDateTime.parse(dateTime);
        return getLocalDateTime(localDateTime);
    }

}
